<script setup>
import { reactive, ref, inject } from 'vue';
import { showToast, showDialog, showLoadingToast, closeToast } from 'vant';
import { getUrlParam, webRequestPayment, navigateTo } from '@/utils';
import { CreateRemark, CreateAddress, CustomerRecord } from '../components';
import store from '@/utils/store';
import useThrottle from '@/utils/useThrottle';
import api from '@/api';
const $logger = inject('logger');

import defaultUser from '@/assets/images/default-user.png';
const maxLength = ref(8);

const props = defineProps({
    merchantNo: {
        type: String,
        value: ''
    }
});

const state = reactive({
    isLoading: true,
    showRemarkPopup: false,
    remark: '',
    userAvatar: defaultUser,
    payMoney: '',
    sellerInfo: null,
    editAuthHeaderNickAble: true,
    expired: false, // 收款码失效
    h5PayMerchantNo: props.merchantNo, // H5 对应商户号
    detail: {
        teamId: '',
        turId: '',
        prohibitedPay: false
    },
    isSubmit: false,
    collectMoneyConfig: {
        receiveInfoSwitch: false
    },
    userReceiveAddress: {
        receiveAddressId: '',
        name: '',
        phone: '',
        province: '',
        city: '',
        area: '',
        detail: ''
    },
    showCustomerRecord: false,
    onlyShow: false
});
const showAddressPopup = ref(false);
const addressState = reactive({
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    detail: ''
});

const getCodeInfo = async (callback) => {
    const turId = getUrlParam('turId');
    const appRoute = getUrlParam('appRoute');
    store.set('PAGE_ID', '10001'); // 设置页面ID
    try {
        const res = await api.fetchGet('getInfoForCollect', { turId, appRoute }, { hasErr: true });
        const { code, data, message } = res || {};
        if (code === 0) {
            const {
                sellerInfo,
                sellerTeamId,
                editAuthHeaderNickAble,
                expired,
                collectMoneyConfig,
                userReceiveAddress,
                buyerImageHerderList,
                lastPayTime,
                payCount
            } = data;
            const { prohibitedPay, sellerHeader } = sellerInfo;

            state.sellerInfo = sellerInfo;
            state.userAvatar = sellerHeader
                ? `${sellerHeader}?imageMogr2/thumbnail/200x200`
                : defaultUser;
            state.editAuthHeaderNickAble = editAuthHeaderNickAble;
            state.expired = expired;
            state.sellerTeamId = sellerTeamId;
            state.detail = {
                teamId: sellerTeamId,
                prohibitedPay,
                turId
            };
            state.userReceiveAddress = userReceiveAddress || {};
            state.collectMoneyConfig = collectMoneyConfig;
            state.payCount = payCount;
            state.lastPayTime = lastPayTime;
            state.buyerImageHerderList = buyerImageHerderList;
            state.isLoading = false;
            checkCustomerInfoShow();

            if (expired) {
                // 收款码已失效
                state.errorInfo = {
                    iconName: 'error',
                    iconColor: '#F1B000',
                    title: message,
                    infoText: '请通知商家重新生成付款链接'
                };
                return;
            }

            if (prohibitedPay) {
                showDialog({
                    title: '商户收款功能已被关闭，无法付款',
                    confirmButtonText: '确定'
                });
            } else {
                typeof callback === 'function' && callback();
            }
        } else {
            showToast(message);
            state.isLoading = false;
        }
    } catch (err) {
        state.isLoading = false;
        console.log(err);
        $logger.error(err, {
            pageId: 10001,
            moduleCode: 'ORDER',
            tag: 'getInfoForCollect接口异常',
            uri: 'order/collectMoney/collect/getInfoForCollect'
        });
        showToast('获取收款信息失败');
    }
};

/**
 * 点支付按钮未授权，授权后回来直接拉起支付
 */
const authBackAction = () => {
    getCodeInfo(() => {
        const detail = store.get('DETAIL_INFO');
        if (detail) {
            state.remark = detail.remark;
            state.payMoney = detail.payMoney;
            state.userReceiveAddress = detail.userReceiveAddress;
            store.remove('DETAIL_INFO');
        }
        handleConfirmKey();
    });
};

const handleConfirmKey = useThrottle(() => {
    const { payMoney, detail, remark, userReceiveAddress, collectMoneyConfig } = state;
    const { teamId, turId, prohibitedPay } = detail;

    // 防止多次点击
    if (state.isSubmit) {
        return;
    }
    state.isSubmit = true;

    //禁止支付
    if (prohibitedPay) {
        showDialog({
            title: '商户收款功能已被关闭，无法付款',
            confirmButtonText: '确定'
        });
        state.isSubmit = false;
        return;
    }

    if (Number(payMoney) < 0.1) {
        showDialog({
            title: '最低付款0.1元',
            confirmButtonText: '好'
        });
        state.isSubmit = false;
        return;
    }

    if (Number(payMoney) > 100000) {
        showDialog({
            title: '单次付款上限10万元，请减少付款金额后重试',
            confirmButtonText: '好'
        });
        state.isSubmit = false;
        return;
    }

    // 校验地址
    if (
        (!userReceiveAddress || !userReceiveAddress.receiveAddressId) &&
        collectMoneyConfig.receiveInfoSwitch
    ) {
        showToast('请填写收货信息');
        onAddAddress();
        state.isSubmit = false;
        return;
    }

    let receiveAddressId = collectMoneyConfig.receiveInfoSwitch
        ? userReceiveAddress.receiveAddressId
        : '';

    const { userStatus, openId } = store.get('USERINFO');
    if (userStatus !== 'AUTHED') {
        store.set('DETAIL_INFO', { remark, payMoney });
        navigateTo('/auth');
        state.isSubmit = false;
        return;
    }

    const param = {
        sellerTeamId: teamId,
        turId,
        remark,
        remarkList: [],
        amount: payMoney,
        receiveAddressId,
        openId
    };

    createOrder(param);
}, 3000);

// 创建订单
const createOrder = async (param) => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
    });
    try {
        const res = await api.fetchPost('createOrder', param, { hasErr: true });
        const { code, message, data } = res;
        if (code === 0) {
            const { orderId } = data;
            requestPayment({
                orderId,
                turId: param.turId,
                h5PayMerchantNo: state.h5PayMerchantNo
            });
        } else if (code === 4008013) {
            // 未升级电签支付拦截
            state.isSubmit = false;
            closeToast();
            showDialog({
                title: message,
                message: '应三方支付机构监管要求，需完成协议签约后方可收款',
                confirmButtonText: '确认'
            });
        } else if (code === 4008011) {
            state.isSubmit = false;
            closeToast();
            // 请通知商家完成商户认证
            showDialog({
                title: message,
                message: '根据国家法规要求，需要完成商户认证后方可收款',
                confirmButtonText: '确认'
            });
        } else if (code === 4000003) {
            // 超出该商户单笔可收款金额上限
            state.isSubmit = false;
            closeToast();
            showDialog({
                title: message,
                confirmButtonText: '确定'
            });
        } else {
            state.isSubmit = false;
            showToast(message);
        }
    } catch (err) {
        state.isSubmit = false;
        console.log(err);
        showToast('创建支付单失败');
    }
};

// 发起支付
const requestPayment = async (param) => {
    const res = await api.fetchPost('orderToPay', param, { hasErr: true });
    const { code, message, data } = res;
    if (code === 0) {
        store.remove('AUTH_TYPE');
        webRequestPayment(data);
        closeToast();
    } else if (code === 2002015 || code === 2002013 || code === 2002011) {
        closeToast();
        // 2002015 你非当前商家客户，无法付款
        // 2002013 商家收款已关闭
        // 2002011 该商家当日收款已达上限
        showDialog({
            title: message,
            confirmButtonText: '确定'
        });
    } else if (code === 2002016) {
        // 收款码已失效
        state.errorInfo = {
            iconName: 'error',
            iconColor: '#F1B000',
            title: message,
            infoText: '请通知商家重新生成付款链接'
        };
    } else {
        showToast(message);
    }
    state.isSubmit = false;
};

const onAddRemark = () => {
    state.showRemarkPopup = true;
};

const onRemarkClose = () => {
    state.showRemarkPopup = false;
};

const onRemarkChange = (value) => {
    state.showRemarkPopup = false;
    state.remark = value;
    checkCustomerInfoShow();
};

/**
 * 显示添加地址
 */
const onAddAddress = () => {
    showAddressPopup.value = true;
    const {
        name = '',
        phone = '',
        province = '',
        city = '',
        area = '',
        detail = ''
    } = state.userReceiveAddress;
    Object.assign(addressState, {
        name,
        phone,
        detail,
        province,
        city,
        area
    });
};

/**
 * 关闭地址
 */
const onAddressClose = () => {
    showAddressPopup.value = false;
};

/**
 * 提交地址
 */
const onAddressChange = (value) => {
    state.userReceiveAddress = value;
    showAddressPopup.value = false;
    checkCustomerInfoShow();
};

const onKeyborderChange = (e) => {
    let payMoney = state.payMoney;
    let value = e.target.innerText || e.srcElement.innerText;
    if (
        /^(([1-9]\d{1,5})|\d)(\.\d{1,2}){0,1}$/.test(value) ||
        (/^\d+$/.test(payMoney) && value === '.')
    ) {
        if (payMoney === '0' && value !== '.') {
            return;
        } else {
            const curIndex = payMoney.indexOf('.');
            if (curIndex !== -1 && payMoney.length > curIndex + 2) {
                value = payMoney.slice(0, curIndex + 3);
            } else {
                value = `${payMoney}${value}`;
            }
            if (value.length > maxLength.value) {
                value = value.slice(0, maxLength.value);
            }
        }
    } else {
        return;
    }
    state.payMoney = value;
    console.log('keyborderInput==', value);
};

const handleCustomerRecord = () => {
    state.showCustomerRecord = true;
};

/**
 * 检查是否仅显示客户购买信息
 */
const checkCustomerInfoShow = () => {
    if (state.remark || state.collectMoneyConfig.receiveInfoSwitch) {
        state.onlyShow = false;
    } else {
        state.onlyShow = true;
    }
};

const handleDeleteKey = () => {
    let payMoney = state.payMoney;
    const value = payMoney && payMoney.length !== 1 ? payMoney.slice(0, payMoney.length - 1) : '';
    state.payMoney = value;
};

defineExpose({ getCodeInfo, authBackAction, handleConfirmKey });
</script>

<template>
    <c-page :loading="state.isLoading">
        <c-result
            v-if="state.errorInfo"
            :icon-name="state.errorInfo.iconName"
            :icon-color="state.errorInfo.iconColor"
            :title="state.errorInfo.title"
            :info-text="state.errorInfo.infoText"
            :btn-type="state.errorInfo.btnType"
            :btn-name="state.errorInfo.buttonName"
        ></c-result>
        <div class="order-pay" v-if="!state.expired && !state.errorInfo">
            <div class="user-info">
                <img class="header-img" :src="state.userAvatar" />
                <div class="seller-info">
                    <div class="name ellipsis-one">{{
                        state.sellerInfo && state.sellerInfo.sellerName
                    }}</div>
                </div>
            </div>
            <div class="pay-content">
                <div class="input-section">
                    <div class="label">
                        <div class="title">付款金额</div>
                    </div>
                    <div class="input-box">
                        <div class="unit">¥</div>
                        <div class="value">{{ state.payMoney }}</div>
                        <div class="focus"></div>
                    </div>
                </div>
                <div class="content-box">
                    <div class="cell-group">
                        <div
                            class="activity-info"
                            :style="`border-radius: ${
                                state.onlyShow ? '10px' : '10px 10px 0 10px'
                            };border-bottom: ${state.onlyShow ? 'none' : '1px solid #ffffff'};`"
                            @click="handleCustomerRecord"
                            v-if="state.payCount > 0"
                        >
                            <div class="left-box">
                                <div
                                    style="height: 20px"
                                    v-for="(item, index) in state.buyerImageHerderList"
                                    :key="index"
                                >
                                    <img
                                        wx:if="{{index < 3}}"
                                        :src="
                                            !item || item === '/images/default-goods.png'
                                                ? defaultGood
                                                : item + '?imageMogr2/thumbnail/40x40'
                                        "
                                        class="buyer-img"
                                        :style="`z-index:${
                                            state.buyerImageHerderList.length - index - 1
                                        };margin-right: ${
                                            state.buyerImageHerderList.length - 1 > index
                                                ? '-10px'
                                                : '0'
                                        }`"
                                    />
                                </div>
                                <div class="time">{{ state.lastPayTime }}</div>
                            </div>
                            <div class="right-box">
                                <div class="person-num">{{ state.payCount }}人已付款</div>
                                <c-icon name="arrow" size="17" color="#07C160" />
                            </div>
                        </div>
                        <van-cell
                            class="note-cell"
                            :style="{ borderRadius: state.remark ? '10px 10px 0 0' : '10px' }"
                            icon-prefix="icon"
                            icon="message1"
                            is-link
                            v-if="state.collectMoneyConfig.receiveInfoSwitch"
                            :border="state.remark"
                            @click="onAddAddress"
                        >
                            <template #icon>
                                <c-icon name="location1" color="#555555" />
                            </template>
                            <template #title>
                                <div>
                                    <div
                                        class="title"
                                        v-if="
                                            state.userReceiveAddress.name ||
                                            state.userReceiveAddress.phone
                                        "
                                    >
                                        {{ state.userReceiveAddress.name }}
                                        {{ state.userReceiveAddress.phone }}
                                    </div>
                                    <div v-else class="title">请填写收货信息</div>
                                    <div class="desc" v-if="state.userReceiveAddress.province">
                                        {{ state.userReceiveAddress.province
                                        }}{{ state.userReceiveAddress.city
                                        }}{{ state.userReceiveAddress.area
                                        }}{{ state.userReceiveAddress.detail }}
                                    </div>
                                </div>
                            </template>
                        </van-cell>
                        <van-cell
                            class="note-cell"
                            v-if="state.remark"
                            :style="{
                                borderRadius:
                                    state.collectMoneyConfig.receiveInfoSwitch || state.payCount > 0
                                        ? ' 0 0 10px 10px'
                                        : '10px'
                            }"
                            :title="state.remark"
                            icon-prefix="icon"
                            icon="message1"
                            is-link
                            @click="onAddRemark"
                        >
                            <template #icon>
                                <c-icon name="message1" color="#555555" />
                            </template>
                        </van-cell>
                    </div>

                    <div class="add-remark" v-if="!state.remark" @click="onAddRemark">添加备注</div>
                </div>
                <div class="keyborder-box" @click="onKeyborderChange">
                    <div class="key-cell">
                        <div class="key-item" data-value="1">1</div>
                        <div class="key-item" data-value="2">2</div>
                        <div class="key-item" data-value="3">3</div>
                        <div class="key-item" data-value="del" @click.stop="handleDeleteKey()">
                            <img src="~@/assets/images/icon-del.png" class="icon-del" />
                        </div>
                    </div>
                    <div class="key-cell">
                        <div class="key-left">
                            <div class="row-cell">
                                <div class="key-item" data-value="4">4</div>
                                <div class="key-item" data-value="5">5</div>
                                <div class="key-item" data-value="6">6</div>
                            </div>
                            <div class="row-cell">
                                <div class="key-item" data-value="7">7</div>
                                <div class="key-item" data-value="8">8</div>
                                <div class="key-item" data-value="9">9</div>
                            </div>
                            <div class="row-cell">
                                <div class="key-item key-zero" data-value="0">0</div>
                                <div class="key-item" data-value=".">.</div>
                            </div>
                        </div>
                        <div
                            class="key-item key-confirm"
                            data-value="confirm"
                            @click.stop="handleConfirmKey"
                        >
                            付款
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </c-page>
    <create-remark
        :show="state.showRemarkPopup"
        :init-data="state.remark"
        @close="onRemarkClose"
        @change="onRemarkChange"
    ></create-remark>
    <create-address
        :show="showAddressPopup"
        :init-data="addressState"
        @close="onAddressClose"
        @change="onAddressChange"
    >
    </create-address>
    <CustomerRecord
        v-model:show="state.showCustomerRecord"
        :order-id="state.sellerTeamId"
    ></CustomerRecord>
</template>

<style scoped lang="less">
@import './index.less';
</style>
